package Scenes
{
	import Audio.SoundScene;
	
	import Config.GameConfig;
	
	import Input.GameInput;
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.getTimer;

    public class GameSceneStack 
	{
        public static var gss:GameSceneStack;
		
        private var elapsedTicks:int;
		private var gameMain:Sprite;
		public var fadeObject:SceneFade;
		private var currentScene:GameScene;
		public var stage:Stage;
		private var lastTicks:int;
		
        public function GameSceneStack(_gameMain:Sprite)
		{
            super();
			gameMain=_gameMain;
			stage=gameMain.stage;
			new GameInput(stage);
			stage.addEventListener(Event.RESIZE,onScreenResize);
			new SoundScene();
			onScreenResize();
            gss = this;
        }
        public function update():void
		{
            var currentTicks:int = getTimer();
            elapsedTicks = elapsedTicks + (currentTicks - lastTicks);
            lastTicks = currentTicks;
            var maxLoop:int = (elapsedTicks - elapsedTicks % GameConfig.interval) / GameConfig.interval;
            elapsedTicks = elapsedTicks % GameConfig.interval;
            var loop:int=0;
            while (loop < maxLoop) 
			{
				if(fadeObject)
				{
					fadeObject.update();
				}
				if(currentScene)
				{
					currentScene.update();
				}
				SoundScene.ss.update();
				loop++;
            }
			if(fadeObject&&fadeObject.removed)
			{
				fadeObject=null;
			}
        }
		private function onScreenResize(event:Event=null):void
		{
			GameConfig.width=stage.stageWidth;
			GameConfig.height=stage.stageHeight;
			if(currentScene)
			{
				currentScene.onScreenResize();
			}
		}
        public function pushScene(nextScene:GameScene,fade:Boolean=true):void
		{
			if(fade)
			{
				if(fadeObject)
				{
					fadeObject.remove();
				}
				fadeObject=new GameConfig.fadeClass();
				fadeObject.gss=this;
				fadeObject.currentScene=currentScene;
				fadeObject.nextScene=nextScene;
			}
			else
			{
				if(currentScene)
				{
					currentScene.destroy();
				}
				currentScene=nextScene;
				currentScene.register(gameMain);
				currentScene.update();
			}
        }
    }
}